package com.fjwt.gz.proxy.ctrl.audit;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.components.oss.model.OssFileConfig;
import com.fjwt.gz.components.oss.service.OssFileService;
import com.fjwt.gz.core.entity.SysUser;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.dto.AuAuditRecordsDTO;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.AwardCouponEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.AuAuditRecordsVO;
import com.fjwt.gz.db.vo.OssRecordVO;
import com.fjwt.gz.proxy.ctrl.CommonCtrl;
import com.fjwt.gz.proxy.util.FileParamsUtil;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 活动审批记录Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/auditRecords")
public class AuditRecordsController extends CommonCtrl {

    @Autowired
    private AuAuditRecordsService auditRecordsService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardCouponService couponService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private OssFileService ossFileService;
    @Autowired
    private AuAuditOssService auditOssService;

    /**
     * 获取审批记录列表
     *
     * @return
     */
    @PostMapping("/getList")
    public ApiRes getList() {
        AuAuditRecordsDTO auditRecordsDTO = getObject(AuAuditRecordsDTO.class);
        auditRecordsDTO.setInfoType("proxy");
        auditRecordsDTO.setAgentNo(getCurrentAgentNo());
        log.info("机构端获取审批记录列表接口，请求地址：/api/auditRecords/getList，请求参数：{}", JSONUtil.toJsonStr(auditRecordsDTO));
        IPage<AuAuditRecordsVO> page = auditRecordsService.selectAuditRecordList(getIPage(true), auditRecordsDTO);
        log.info("机构端获取审批记录列表接口，请求地址：/api/auditRecords/getList，返回参数：{}", JSONUtil.toJsonStr(page));
        return ApiRes.page(page);
    }


    /**
     * 进行审批
     *
     * @return
     */
    @PostMapping("/audit")
    public ApiRes audit() {
        AuAuditRecordsDTO auditRecordsDTO = getObject(AuAuditRecordsDTO.class);
        log.info("机构端进行审批接口，请求地址：/api/auditRecords/audit，请求参数：{}", JSONUtil.toJsonStr(auditRecordsDTO));
        SysUser sysUser = getCurrentUser().getSysUser();
        auditRecordsService.audit(auditRecordsDTO, sysUser);
        // TODO进行插表OSS
        if(StringUtils.isNoneBlank(auditRecordsDTO.getOssFileUrl())){
            auditOssService.saveRecord(auditRecordsDTO.getActivityId(),auditRecordsDTO.getAuditRecordsId(),auditRecordsDTO.getOssFileUrl(),getCurrentUser().getSysUserId(),2);
        }
        return ApiRes.ok();
    }


    /**
     * 撤销审批
     *
     * @return
     */
    @PostMapping("/revoke")
    public ApiRes revoke() {
        AuAuditRecordsDTO auditRecordsDTO = getObject(AuAuditRecordsDTO.class);
        log.info("pc端进行审批接口，请求地址：/api/auditRecords/audit，请求参数：{}", JSONUtil.toJsonStr(auditRecordsDTO));
        SysUser sysUser = getCurrentUser().getSysUser();
        auditRecordsService.revoke(auditRecordsDTO, sysUser);
        return ApiRes.ok();
    }

    /**
     * 卡券参数回执
     *
     * @return
     */
    @PostMapping("/couponReceiptInfo")
    public ApiRes couponReceiptInfo() {
        AuAuditRecordsDTO recordDTO = getObject(AuAuditRecordsDTO.class);
        log.info("机构端卡券参数回执接口，请求地址：/api/auditRecords/couponReceiptInfo，请求参数：{}", JSONUtil.toJsonStr(recordDTO));
        auditRecordsService.couponReceiptInfo(recordDTO);
        return ApiRes.ok();
    }

    /**
     * 下载设置函
     * @return
     * @throws Exception
     */
    @PostMapping("/downLetter")
    public ApiRes downLetter()throws Exception{
        String zipFile = "letter.zip";
        Long activityId = getValLong("activityId");
        Long auditRecordsId = getValLong("auditRecordsId");
        Integer fileType = getValInteger("fileType");
        if(ObjectUtils.isEmpty(activityId) || ObjectUtils.isEmpty(auditRecordsId) || ObjectUtils.isEmpty(fileType)){
            throw new BizException("请求参数缺失");
        }
        if (fileType == 1) {
            OssRecordVO ossRecordVO = auditOssService.getLastAuditActivityOss(activityId, fileType);
            if (ObjectUtils.isNotEmpty(ossRecordVO) && ObjectUtils.isNotEmpty(ossRecordVO.getOssUrl())) {
                return ApiRes.ok(ossRecordVO.getOssUrl());
            }

            List<ActivityAwardVO> list = activityAwardService.getBaseMapper().queryList(activityId);
            if (list.size() <= 0) {
                throw new BizException("卡券配置有误");
            }
            Map<String, Object> dataMap = new HashMap<>();
            ActivityEntity activityEntity = activityService.getById(activityId);
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            for (ActivityAwardVO v : list) {
                if (0 == v.getAwardType()) {
                    AwardCouponEntity coupon = couponService.getById(v.getAwardId());
                    File file = FileParamsUtil.toExportWordDataMap(dataMap, activityEntity, coupon);
                    if (!file.exists()) {
                        throw new BizException("生成文件异常");
                    }
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = fis.read(bytes)) >= 0) {
                            zos.write(bytes, 0, length);
                        }
                    } finally {
                        try {
                            fis.close();
                        } catch (Exception e) {
                        }
                        if (file != null) {
                            file.delete();
                        }
                    }
                }
            }
            try {
                zos.close();
            } catch (Exception e) {
            }

            try {
                fos.close();
            } catch (Exception e) {
            }

            File file = new File(zipFile);
            FileInputStream inputStream = new FileInputStream(file);
            // 创建MockMultipartFile对象
            MultipartFile multipartFile = new MockMultipartFile(
                    "file",            // 名称，可以自定义
                    file.getName(),          // 原始文件名
                    "text/plain",            // 内容类型，可以根据文件实际类型修改
                    inputStream              // 文件输入流
            );
            String url = ossFileService.singleFileUpload(multipartFile, OssFileConfig.BIZ_TYPE.UPLOAD);
            if (null != file) {
                file.delete();
            }
            // TODO进行插表OSS
            auditOssService.saveRecord(activityId, auditRecordsId, url, getCurrentUser().getSysUserId(), 1);
            return ApiRes.ok(url);
        }else {
            OssRecordVO ossRecordVO = auditOssService.getLastAuditActivityOss(activityId, fileType);
            if (ObjectUtils.isNotEmpty(ossRecordVO) && ObjectUtils.isNotEmpty(ossRecordVO.getOssUrl())) {
                return ApiRes.ok(ossRecordVO.getOssUrl());
            }else {
                throw new BizException("下级未回传配置函");
            }
        }
    }

}
